package image

import (
	"crypto/tls"
	"fmt"
	"io"
	"net/http"

	"gitee.com/smewl13/registry-sync/v2/logger"
)

func RequestGet(tlsFlag bool, url, token string) *http.Response {
	tr := &http.Transport{DisableKeepAlives: true}
	if tlsFlag {
		tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
	}
	client := &http.Client{Transport: tr}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		logger.Errorf("生成请求失败, url: %v, err: %v", url, err)
		return nil
	}
	req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json")
	req.Header.Set("Authorization", token)

	resp, err := client.Do(req)
	if err != nil {
		logger.Errorf("请求失败, url: %v, err: %v", url, err)
		return nil
	}

	if resp.StatusCode != 200 {
		defer resp.Body.Close()
		logger.Errorf("请求失败, url: %v, Header: %#v, code: %d", url, req.Header, resp.StatusCode)
		return nil
	}

	return resp
}

func Request(tlsFlag bool, url, token string) []byte {
	resp := RequestGet(tlsFlag, url, token)
	if resp == nil {
		return nil
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logger.Errorf("获取结果失败, url: %v, err: %v", url, err)
		return nil
	}

	return body
}

func Login(tlsFlag bool, url string) (string, error) {
	resp := RequestGet(tlsFlag, url, "")
	if resp == nil {
		return "", fmt.Errorf("认证失败")
	}
	defer resp.Body.Close()
	token := resp.Request.Header.Get("Authorization")
	return token, nil
}
